<?php

require_once 'business/AccountManager.php';
require_once 'const/RequestConst.php';

class OrderController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {
        // action body
    }

    public function cartAction() {
        $this->view->admin = true;
        $request = $this->getRequest();
        $cmd = $request->getParam("cmd");
        $pid = $request->getParam("id");
        if ($cmd == "delete") {
            $session = new Zend_Session_Namespace("default", true);
            $carts = $session->carts;
            $index = 0;
            for (; $index < count($carts); $index++) {
                if ($carts[$index]->getProductID() == $pid) {
                    break;
                }
            }
            array_splice($session->carts, $index, 1);
        } else if ($cmd == "clear") {
            $session = new Zend_Session_Namespace("default", true);
            unset($session->carts);
        } else if ($cmd == "modify") {
            $nums = $request->getParam("num");
            $session = new Zend_Session_Namespace("default", true);
            $carts = $session->carts;
            $index = 0;
            for (; $index < count($carts); $index++) {
                $num = $nums[$index];
                if ($num > 0) {
                    $carts[$index]->setNumber($num);
                }
            }
        } else {
            $session = new Zend_Session_Namespace("default", true);
            if (strlen($pid) != 0) {
                Application_Model_CartMapper::addToCarts($pid, $session);
            }
        }
        $carts = Application_Model_CartMapper::getCarts($session);
        $this->view->carts = $carts;
    }

    public function buyAction() {
        $request = $this->getRequest();
        $session = new Zend_Session_Namespace("default", true);
        $carts = Application_Model_CartMapper::getCarts($session);
        if ($request->isGet()) {
            $this->view->carts = $carts;
        } else {
            Business_AccountManager::requireLogin($this->getResponse(), LOGIN_URL, "/order/buy");
            if (Business_AccountManager::getUserIdentity() != null) {
                $email = Business_AccountManager::getUserIdentity();
                $accountID = Application_Model_AccountMapper::getIDByEmail($email);
                foreach ($carts as $cart) {
                    $productID = $cart->getProductID();
                    $num = $cart->getNumber();
                    Application_Model_ProductMapper::buy($productID, $accountID, $num);
                }
                unset($session->carts);
                $this->getResponse()->setRedirect("/profile/list");
            }
        }
    }

}

